import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

# 生成3分类的数据集
n_classes = 3
X, y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10,
                           n_classes=n_classes, n_clusters_per_class=1, random_state=42)

# 使用LDA进行降维
lda = LinearDiscriminantAnalysis(n_components=n_classes - 1)
X_r2 = lda.fit(X, y).transform(X)

# 颜色列表（数量要和n_classes一致）
colors = ['navy', 'turquoise', 'darkorange']

# 绘制LDA降维后的数据
plt.figure()
for color, i in zip(colors, [0, 1, 2]):
    plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color,
                label=f'Class {i}')
plt.legend(loc='best', shadow=False, scatterpoints=1)

plt.title('LDA of 3-Class Synthetic Dataset')
plt.xlabel('LD1')
plt.ylabel('LD2')

plt.show()
